/**
 * 通用js方法封装处理
 */
var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        return {//移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            symbian: u.indexOf('SymbianOS') > -1, //塞班内核
            windowsPhone: u.indexOf('Windows Phone') > -1, // 微软手机内核
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            iPod: u.indexOf('iPod') > -1, //是否iPod
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信
            qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
    }(),
    language:(navigator.browserLanguage || navigator.language).toLowerCase()
};
// 判断PC端
var isPC = function () {
    if(!browser.versions.mobile && !browser.versions.ios && !browser.versions.android &&
        !browser.versions.iPhone && !browser.versions.symbian && !browser.versions.windowsPhone &&
        !browser.versions.iPod && !browser.versions.iPad && !browser.versions.weixin){
        return true;
    }else {
        return false;
    }
};
// 当前table相关信息
var table = {
    config: {},
    // 当前实例配置
    options: {},
    // 设置实例配置
    set: function (id) {
        if ($.common.getLength(table.config) > 1) {
            var tableId = $.common.isEmpty(id) ? $(event.currentTarget).parents(".bootstrap-table").find(".table").attr("id") : id;
            if ($.common.isNotEmpty(tableId)) {
                table.options = table.get(tableId);
            }
        }
    },
    // 获取实例配置
    get: function (id) {
        return table.config[id];
    },
    // 记住选择实例组
    rememberSelecteds: {},
    // 记住选择ID组
    rememberSelectedIds: {}
};

// 表格-更多操作-头部
var moreBtnStart = "<div class='btn-group'>" +
    "<button class='btn am-btn-primary btn-xs dropdown-toggle' data-toggle='dropdown'><i class='caret'></i> 更多操作</button>" +
    "<ul class='dropdown-menu' style='min-width:100px;right:0px;left: auto;'>";
// 表格-更多操作-尾部
var moreBtnEnd = "</ul></div>";

(function ($) {
    $.extend({
        _tree: {},
        bttTable: {},
        // 表格封装处理
        table: {
            // 初始化表格参数
            init: function (options) {
                var defaults = {
                    id: "bootstrap-table",
                    type: 0, // 0 代表bootstrapTable 1代表bootstrapTreeTable
                    height: undefined,
                    sidePagination: "server",
                    sortName: "",
                    sortOrder: "asc",
                    pagination: true,
                    paginationLoop: false,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100, 200, 500, 1000, 2000],
                    toolbar: "toolbar",
                    striped: true,
                    escape: false,
                    firstLoad: true,
                    showFooter: false,
                    search: false,
                    showSearch: true,
                    showPageGo: false,
                    showRefresh: true,
                    showColumns: true,
                    showToggle: false,
                    showExport: true,
                    clickToSelect: false,
                    singleSelect: false,
                    mobileResponsive: true,
                    rememberSelected: false,
                    fixedColumns: false,
                    fixedNumber: 0,
                    rightFixedColumns: false,
                    rightFixedNumber: 0,
                    queryParams: $.table.queryParams,
                    rowStyle: {},
                };
                var options = $.extend(defaults, options);
                table.options = options;
                table.config[options.id] = options;
                $.table.initEvent();
                $('#' + options.id).bootstrapTable({
                    id: options.id,
                    url: options.url,                                   // 请求后台的URL（*）
                    contentType: "application/x-www-form-urlencoded",   // 编码类型
                    method: 'post',                                     // 请求方式（*）
                    cache: false,                                       // 是否使用缓存
                    height: options.height,                             // 表格的高度
                    striped: options.striped,                           // 是否显示行间隔色
                    sortable: true,                                     // 是否启用排序
                    sortStable: true,                                   // 设置为 true 将获得稳定的排序
                    sortName: options.sortName,                         // 排序列名称
                    sortOrder: options.sortOrder,                       // 排序方式  asc 或者 desc
                    pagination: options.pagination,                     // 是否显示分页（*）
                    paginationLoop: options.paginationLoop,             // 是否启用分页条无限循环的功能
                    pageNumber: 1,                                      // 初始化加载第一页，默认第一页
                    pageSize: options.pageSize,                         // 每页的记录行数（*）
                    pageList: options.pageList,                         // 可供选择的每页的行数（*）
                    firstLoad: options.firstLoad,                       // 是否首次请求加载数据，对于数据较大可以配置false
                    escape: options.escape,                             // 转义HTML字符串
                    showFooter: options.showFooter,                     // 是否显示表尾
                    iconSize: 'xs',                                     // 图标大小：undefined默认的按钮尺寸 xs超小按钮sm小按钮lg大按钮
                    toolbar: "#" + options.toolbar,                     // 指定工作栏
                    sidePagination: options.sidePagination,             // server启用服务端分页client客户端分页
                    search: options.search,                             // 是否显示搜索框功能
                    searchText: options.searchText,                     // 搜索框初始显示的内容，默认为空
                    showSearch: options.showSearch,                     // 是否显示检索信息
                    showPageGo: options.showPageGo,               		// 是否显示跳转页
                    showRefresh: options.showRefresh,                   // 是否显示刷新按钮
                    showColumns: options.showColumns,                   // 是否显示隐藏某列下拉框
                    showToggle: options.showToggle,                     // 是否显示详细视图和列表视图的切换按钮
                    showExport: options.showExport,                     // 是否支持导出文件
                    showHeader: options.showHeader,                     // 是否显示表头
                    showFullscreen: options.showFullscreen,             // 是否显示全屏按钮
                    uniqueId: options.uniqueId,                         // 唯 一的标识符
                    clickToSelect: options.clickToSelect,				// 是否启用点击选中行
                    singleSelect: options.singleSelect,                 // 是否单选checkbox
                    mobileResponsive: options.mobileResponsive,         // 是否支持移动端适配
                    cardView: options.cardView,                         // 是否启用显示卡片视图
                    detailView: options.detailView,                     // 是否启用显示细节视图
                    onClickRow: options.onClickRow,                     // 点击某行触发的事件
                    onDblClickRow: options.onDblClickRow,               // 双击某行触发的事件
                    onClickCell: options.onClickCell,                   // 单击某格触发的事件
                    onDblClickCell: options.onDblClickCell,             // 双击某格触发的事件
                    onEditableSave: options.onEditableSave,             // 行内编辑保存的事件
                    onExpandRow: options.onExpandRow,                   // 点击详细视图的事件
                    rememberSelected: options.rememberSelected,         // 启用翻页记住前面的选择
                    fixedColumns: options.fixedColumns,                 // 是否启用冻结列（左侧）
                    fixedNumber: options.fixedNumber,                   // 列冻结的个数（左侧）
                    rightFixedColumns: options.rightFixedColumns,       // 是否启用冻结列（右侧）
                    rightFixedNumber: options.rightFixedNumber,         // 列冻结的个数（右侧）
                    onReorderRow: options.onReorderRow,                 // 当拖拽结束后处理函数
                    queryParams: options.queryParams,                   // 传递参数（*）
                    rowStyle: options.rowStyle,                         // 通过自定义函数设置行样式
                    columns: options.columns,                           // 显示列信息（*）
                    data: options.data,                                 // 被加载的数据
                    responseHandler: $.table.responseHandler,           // 在加载服务器发送来的数据之前处理函数
                    onLoadSuccess: $.table.onLoadSuccess,               // 当所有数据被加载时触发处理函数
                    exportOptions: options.exportOptions,               // 前端导出忽略列索引
                    detailFormatter: options.detailFormatter,           // 在行下面展示其他数据列表
                });
            },
            // 获取实例ID，如存在多个返回#id1,#id2 delimeter分隔符
            getOptionsIds: function (separator) {
                var _separator = $.common.isEmpty(separator) ? "," : separator;
                var optionsIds = "";
                $.each(table.config, function (key, value) {
                    optionsIds += "#" + key + _separator;
                });
                return optionsIds.substring(0, optionsIds.length - 1);
            },
            // 查询条件
            queryParams: function (params) {
                var curParams = {
                    // 传递参数查询参数
                    pageSize: params.limit,
                    pageNum: params.offset / params.limit + 1,
                    searchValue: params.search,
                    orderByColumn: params.sort,
                    isAsc: params.order
                };
                var currentId = $.common.isEmpty(table.options.formId) ? $('form').attr('id') : table.options.formId;
                return $.extend(curParams, $.common.formToJSON(currentId));
            },
            // 请求获取数据后处理回调函数
            responseHandler: function (res) {
                if (typeof table.options.responseHandler == "function") {
                    table.options.responseHandler(res);
                }
                if (res.code == 0) {
                    if ($.common.isNotEmpty(table.options.sidePagination) && table.options.sidePagination == 'client') {
                        return res.rows;
                    } else {
                        if ($.common.isNotEmpty(table.options.rememberSelected) && table.options.rememberSelected) {
                            var column = $.common.isEmpty(table.options.uniqueId) ? table.options.columns[1].field : table.options.uniqueId;
                            $.each(res.rows, function (i, row) {
                                row.state = $.inArray(row[column], table.rememberSelectedIds[table.options.id]) !== -1;
                            })
                        }
                        return {rows: res.rows, total: res.total};
                    }
                } else {
                    $.modal.alertWarning(res.msg);
                    return {rows: [], total: 0};
                }
            },
            // 初始化事件
            initEvent: function () {
                // 实例ID信息
                var optionsIds = $.table.getOptionsIds();
                // 监听事件处理
                $(optionsIds).on(TABLE_EVENTS, function () {
                    table.set($(this).attr("id"));
                });
                // 选中、取消、全部选中、全部取消（事件）
                $(optionsIds).on("check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table", function (e, rows) {
                    // 复选框分页保留保存选中数组
                    var rowIds = $.table.affectedRowIds(rows);
                    if ($.common.isNotEmpty(table.options.rememberSelected) && table.options.rememberSelected) {
                        func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
                        var selectedIds = table.rememberSelectedIds[table.options.id];
                        if ($.common.isNotEmpty(selectedIds)) {
                            table.rememberSelectedIds[table.options.id] = _[func](selectedIds, rowIds);
                        } else {
                            table.rememberSelectedIds[table.options.id] = _[func]([], rowIds);
                        }
                        var selectedRows = table.rememberSelecteds[table.options.id];
                        if ($.common.isNotEmpty(selectedRows)) {
                            table.rememberSelecteds[table.options.id] = _[func](selectedRows, rows);
                        } else {
                            table.rememberSelecteds[table.options.id] = _[func]([], rows);
                        }
                    }
                });
                // 加载成功、选中、取消、全部选中、全部取消（事件）
                $(optionsIds).on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table load-success.bs.table", function () {
                    var toolbar = table.options.toolbar;
                    var uniqueId = table.options.uniqueId;
                    // 工具栏按钮控制
                    var rows = $.common.isEmpty(uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(uniqueId);
                    // 非多个禁用
                    $('.fw-model-setup-left .multiple').toggleClass('am-disabled', !rows.length);
                    // 非单个禁用
                    $('.fw-model-setup-left .single').toggleClass('am-disabled', rows.length != 1);
                });
                // 图片预览事件
                $(optionsIds).off("click").on("click", '.img-circle', function () {
                    var src = $(this).attr('src');
                    var target = $(this).data('target');
                    if ($.common.equals("self", target)) {
                        var height = $(this).data('height');
                        var width = $(this).data('width');
                        // 如果是移动端，就使用自适应大小弹窗
                        if ($.common.isMobile()) {
                            width = 'auto';
                            height = 'auto';
                        }
                        layer.open({
                            title: false,
                            type: 1,
                            closeBtn: true,
                            shadeClose: false,
                            area: ['auto', 'auto'],
                            content: "<img src='" + src + "' height='" + height + "' width='" + width + "'/>"
                        });
                    } else if ($.common.equals("blank", target)) {
                        window.open(src);
                    }
                });
                // 单击tooltip事件
                $(optionsIds).on("click", '.tooltip-show', function () {
                    var target = $(this).data('target');
                    var input = $(this).prev();
                    if(isPC()){
                        if ($.common.equals("copy", target)) {
                            input.select();
                            document.execCommand("copy");
                        } else if ($.common.equals("open", target)) {
                            parent.layer.alert(input.val(), {
                                title: "信息内容",
                                shadeClose: false,
                                btn: ['确认'],
                                btnclass: ['btn btn-primary'],
                            });
                        }
                    }
                });
            },
            // 当所有数据被加载时触发
            onLoadSuccess: function (data) {
                if (typeof table.options.onLoadSuccess == "function") {
                    table.options.onLoadSuccess(data);
                }
                // 浮动提示框特效
                $(".table [data-toggle='tooltip']").tooltip();
            },
            /**
             * 合并行
             * @param data  原始数据（在服务端完成排序）
             * @param fieldName 合并属性名称数组
             * @param colspan 列数
             * @param target 目标表格对象
             */
            mergeCells: function mergeCells(data, fieldName, colspan, target) {
                if (data.length == 0) {
                    alert("不能传入空数据");
                    return;
                }
                var numArr = [];
                var value = data[0][fieldName];
                var num = 0;
                for (var i = 0; i < data.length; i++) {
                    if (value != data[i][fieldName]) {
                        numArr.push(num);
                        value = data[i][fieldName];
                        num = 1;
                        continue;
                    }
                    num++;
                }
                var merIndex = 0;
                for (var i = 0; i < numArr.length; i++) {
                    $(target).bootstrapTable('mergeCells', {
                        index: merIndex,
                        field: fieldName,
                        colspan: colspan,
                        rowspan: numArr[i]
                    })
                    merIndex += numArr[i];
                }
            },
            /**
             * 合并列
             * @param data  原始数据（在服务端完成排序）
             * @param fieldName 合并属性数组
             * @param target    目标表格对象
             */
            mergeColspan: function (data, fieldNameArr, target) {
                if (data.length == 0) {
                    alert("不能传入空数据");
                    return;
                }
                if (fieldNameArr.length == 0) {
                    alert("请传入属性值");
                    return;
                }
                var num = -1;
                var index = 0;
                for (var i = 0; i < data.length; i++) {
                    num++;
                    for (var v in fieldNameArr) {
                        index = 1;
                        if (data[i][fieldNameArr[v]] != data[i][fieldNameArr[0]]) {
                            index = 0;
                            break;
                        }
                    }
                    if (index == 0) {
                        continue;
                    }
                    $(target).bootstrapTable('mergeCells', {
                        index: num,
                        field: fieldNameArr[0],
                        colspan: fieldNameArr.length,
                        rowspan: 1
                    });
                }
            },
            // 表格销毁
            destroy: function (tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('destroy');
            },
            // 序列号生成
            serialNumber: function (index, tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                var tableParams = $("#" + currentId).bootstrapTable('getOptions');
                var pageSize = tableParams.pageSize == undefined ? 0 : tableParams.pageSize;
                var pageNumber = tableParams.pageNumber == undefined ? 0 : tableParams.pageNumber;
                return pageSize * (pageNumber - 1) + index + 1;
            },
            // 列超出指定长度浮动提示 target（copy单击复制文本 open弹窗打开文本）
            tooltip: function (value, length, target) {
                var _length = $.common.isEmpty(length) ? 20 : length;
                var _text = "";
                var _value = $.common.nullToStr(value);
                var _target = $.common.isEmpty(target) ? 'copy' : target;
                if (_value.length > _length) {
                    _text = _value.substr(0, _length) + "...";
                    _value = _value.replace(/\'/g, "&apos;");
                    _value = _value.replace(/\"/g, "&quot;");
                    var actions = [];
                    actions.push($.common.sprintf('<input style="opacity: 0;position: absolute;z-index:-1" type="text" value="%s"/>', _value));
                    actions.push($.common.sprintf('<div class="am-ellipsis" style="width: %s;" onclick="$.common.copyToClipboard('+_value+');" title="%s">%s</div>', length+'em', _value, _value));
                    return actions.join('');
                } else {
                    _text = _value;
                    return _text;
                }
            },
            // 下拉按钮切换
            dropdownToggle: function (value) {
                var actions = [];
                actions.push('<div class="btn-group">');
                actions.push('<button type="button" class="btn btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">');
                actions.push('<i class="fa fa-cog"></i>&nbsp;<span class="fa fa-chevron-down"></span></button>');
                actions.push('<ul class="dropdown-menu">');
                actions.push(value.replace(/<a/g, "<li><a").replace(/<\/a>/g, "</a></li>"));
                actions.push('</ul>');
                actions.push('</div>');
                return actions.join('');
            },
            // 图片预览
            imageView: function (value, height, width, target) {
                if ($.common.isEmpty(width)) {
                    width = 'auto';
                }
                if ($.common.isEmpty(height)) {
                    height = 'auto';
                }
                // blank or self
                var _target = $.common.isEmpty(target) ? 'self' : target;
                if ($.common.isNotEmpty(value)) {
                    return $.common.sprintf("<img class='img-circle img-xs' data-height='%s' data-width='%s' data-target='%s' src='%s'/>", height, width, _target, value);
                } else {
                    return $.common.nullToStr(value);
                }
            },
            // 搜索-默认第一个form
            search: function (formId, tableId, data) {
                table.set(tableId);
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var params = $.common.isEmpty(tableId) ? $("#" + table.options.id).bootstrapTable('getOptions') : $("#" + tableId).bootstrapTable('getOptions');
                params.queryParams = function (params) {
                    var search = $.common.formToJSON(currentId);
                    if ($.common.isNotEmpty(data)) {
                        $.each(data, function (key) {
                            search[key] = data[key];
                        });
                    }
                    search.pageSize = params.limit;
                    search.pageNum = params.offset / params.limit + 1;
                    search.searchValue = params.search;
                    search.orderByColumn = params.sort;
                    search.isAsc = params.order;
                    return search;
                }
                if ($.common.isNotEmpty(tableId)) {
                    $("#" + tableId).bootstrapTable('refresh', params);
                } else {
                    $("#" + table.options.id).bootstrapTable('refresh', params);
                }
            },
            // 导出数据
            exportExcel: function (formId) {
                table.set();
                $.modal.confirm("确定导出所有" + table.options.modalName + "吗？", function () {
                    var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                    var params = $("#" + table.options.id).bootstrapTable('getOptions');
                    var dataParam = $("#" + currentId).serializeArray();
                    dataParam.push({"name": "orderByColumn", "value": params.sortName});
                    dataParam.push({"name": "isAsc", "value": params.sortOrder});
                    $.modal.loading("正在导出数据，请稍后...");
                    $.post(table.options.exportUrl, dataParam, function (result) {
                        if (result.code == web_status.SUCCESS) {
                            window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                        } else if (result.code == web_status.WARNING) {
                            $.modal.alertWarning(result.msg)
                        } else {
                            $.modal.alertError(result.msg);
                        }
                        $.modal.closeLoading();
                    });
                });
            },
            //下载ftp模板
            downTemplate: function () {
                window.location.href = table.options.downTemplate;
            },
            // 下载模板
            importTemplate: function () {
                table.set();
                $.get(table.options.importTemplateUrl, function (result) {
                    if (result.code == web_status.SUCCESS) {
                        window.location.href = ctx + "common/download?fileName=" + encodeURI(result.msg) + "&delete=" + true;
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                });
            },
            // 导入数据
            importExcel: function (formId) {
                table.set();
                var currentId = $.common.isEmpty(formId) ? 'importForm' : formId;
                $("#" + currentId)[0].reset();
                layer.open({
                    type: 1,
                    area: ['400px', '230px'],
                    fix: false,
                    //不固定
                    maxmin: true,
                    shade: 0.3,
                    title: '导入' + table.options.modalName + '数据',
                    content: $('#' + currentId),
                    btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
                    // 弹层外区域关闭
                    shadeClose: false,
                    btn1: function (index, layero) {
                        var file = layero.find('#file').val();
                        if (file == '' || (!$.common.endWith(file, '.xls') && !$.common.endWith(file, '.xlsx'))) {
                            $.modal.msgWarning("请选择后缀为 “xls”或“xlsx”的文件。");
                            return false;
                        }
                        var index = layer.load(2, {shade: false});
                        $.modal.disable();
                        var formData = new FormData();
                        formData.append("file", $('#file')[0].files[0]);
                        formData.append("updateSupport", $("input[name='updateSupport']").is(':checked'));
                        $.ajax({
                            url: table.options.importUrl,
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            success: function (result) {
                                if (result.code == web_status.SUCCESS) {
                                    $.modal.closeAll();
                                    $.modal.alertSuccess(result.msg);
                                    $.table.refresh();
                                } else if (result.code == web_status.WARNING) {
                                    layer.close(index);
                                    $.modal.enable();
                                    $.modal.alertWarning(result.msg);
                                    $.table.refresh();
                                } else {
                                    layer.close(index);
                                    $.modal.enable();
                                    $.modal.alertError(result.msg);
                                    $.table.refresh();
                                }
                            }
                        });
                    }
                });
            },
            // 刷新表格
            refresh: function (tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('refresh', {
                    silent: true
                });
            },
            // 查询表格指定列值
            selectColumns: function (column) {
                var rows = $.map($("#" + table.options.id).bootstrapTable('getSelections'), function (row) {
                    return row[column];
                });
                if ($.common.isNotEmpty(table.options.rememberSelected) && table.options.rememberSelected) {
                    var selectedRows = table.rememberSelecteds[table.options.id];
                    if ($.common.isNotEmpty(selectedRows)) {
                        rows = $.map(table.rememberSelecteds[table.options.id], function (row) {
                            return row[column];
                        });
                    }
                }
                return $.common.uniqueFn(rows);
            },
            // 获取当前页选中或者取消的行ID
            affectedRowIds: function (rows) {
                var column = $.common.isEmpty(table.options.uniqueId) ? table.options.columns[1].field : table.options.uniqueId;
                var rowIds;
                if ($.isArray(rows)) {
                    rowIds = $.map(rows, function (row) {
                        return row[column];
                    });
                } else {
                    rowIds = [rows[column]];
                }
                return rowIds;
            },
            // 查询表格首列值
            selectFirstColumns: function () {
                var rows = $.map($("#" + table.options.id).bootstrapTable('getSelections'), function (row) {
                    return row[table.options.columns[1].field];
                });
                if ($.common.isNotEmpty(table.options.rememberSelected) && table.options.rememberSelected) {
                    var selectedRows = table.rememberSelecteds[table.options.id];
                    if ($.common.isNotEmpty(selectedRows)) {
                        rows = $.map(selectedRows, function (row) {
                            return row[table.options.columns[1].field];
                        });
                    }
                }
                return $.common.uniqueFn(rows);
            },
            // 回显数据字典
            selectDictLabel: function (datas, value) {
                var actions = [];
                $.each(datas, function (index, dict) {
                    if (dict.dictValue == ('' + value)) {
                        var listClass = $.common.equals("default", dict.listClass) || $.common.isEmpty(dict.listClass) ? "" : "am-badge am-badge-" + dict.listClass + " am-radius";
                        actions.push($.common.sprintf("<span class='%s'>%s</span>", listClass, dict.dictLabel));
                        return false;
                    }
                });
                return actions.join('');
            },
            // 显示表格指定列
            showColumn: function (column, tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('showColumn', column);
            },
            // 隐藏表格指定列
            hideColumn: function (column, tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('hideColumn', column);
            },
            // 显示所有表格列
            showAllColumns: function (tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('showAllColumns');
            },
            // 隐藏所有表格列
            hideAllColumns: function (tableId) {
                var currentId = $.common.isEmpty(tableId) ? table.options.id : tableId;
                $("#" + currentId).bootstrapTable('hideAllColumns');
            }
        },
        // 表格树封装处理
        treeTable: {
            // 初始化表格
            init: function (options) {
                var defaults = {
                    id: "bootstrap-tree-table",
                    type: 1, // 0 代表bootstrapTable 1代表bootstrapTreeTable
                    height: 0,
                    rootIdValue: null,
                    ajaxParams: {},
                    toolbar: "toolbar",
                    striped: false,
                    expandColumn: 1,
                    showSearch: true,
                    showRefresh: true,
                    showColumns: false,
                    expandAll: false,
                    expandFirst: false
                };
                var options = $.extend(defaults, options);
                table.options = options;
                table.config[options.id] = options;
                $.bttTable = $('#' + options.id).bootstrapTreeTable({
                    id: options.id,
                    code: options.code,                                 // 用于设置父子关系
                    parentCode: options.parentCode,                     // 用于设置父子关系
                    type: 'post',                                       // 请求方式（*）
                    url: options.url,                                   // 请求后台的URL（*）
                    data: options.data,                                 // 无url时用于渲染的数据
                    ajaxParams: options.ajaxParams,                     // 请求数据的ajax的data属性
                    rootIdValue: options.rootIdValue,                   // 设置指定根节点id值
                    height: options.height,                             // 表格树的高度
                    expandColumn: options.expandColumn,                 // 在哪一列上面显示展开按钮
                    striped: options.striped,                           // 是否显示行间隔色
                    bordered: false,                                    // 是否显示边框
                    toolbar: '#' + options.toolbar,                     // 指定工作栏
                    showSearch: options.showSearch,                     // 是否显示检索信息
                    showRefresh: options.showRefresh,                   // 是否显示刷新按钮
                    showColumns: options.showColumns,                   // 是否显示隐藏某列下拉框
                    expandAll: options.expandAll,                       // 是否全部展开
                    expandFirst: options.expandFirst,                   // 是否默认第一级展开--expandAll为false时生效
                    columns: options.columns,                           // 显示列信息（*）
                    responseHandler: $.treeTable.responseHandler        // 当所有数据被加载时触发处理函数
                });
            },
            // 条件查询
            search: function (formId) {
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                var params = $.common.formToJSON(currentId);
                $.bttTable.bootstrapTreeTable('refresh', params);
            },
            // 刷新
            refresh: function () {
                $.bttTable.bootstrapTreeTable('refresh');
            },
            // 查询表格树指定列值
            selectColumns: function (column) {
                var rows = $.map($.bttTable.bootstrapTreeTable('getSelections'), function (row) {
                    return row[column];
                });
                return $.common.uniqueFn(rows);
            },
            // 请求获取数据后处理回调函数，校验异常状态提醒
            responseHandler: function (res) {
                console.log(res)
                if (typeof table.options.responseHandler == "function") {
                    table.options.responseHandler(res);
                }
                if (res.code != undefined && res.code != 0) {
                    $.modal.alertWarning(res.msg);
                    return [];
                } else {
                    return res;
                }
            },
        },
        // 表单封装处理
        form: {
            // 表单重置
            reset: function (formId, tableId) {
                table.set(tableId);
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $("#" + currentId)[0].reset();
                $("#" + currentId).find('select').find('option[value=""]').attr('selected', true);
                if (table.options.type == table_type.bootstrapTable) {
                    if ($.common.isEmpty(tableId)) {
                        $("#" + table.options.id).bootstrapTable('refresh');
                    } else {
                        $("#" + tableId).bootstrapTable('refresh');
                    }
                } else if (table.options.type == table_type.bootstrapTreeTable) {
                    if ($.common.isEmpty(tableId)) {
                        $("#" + table.options.id).bootstrapTreeTable('refresh', []);
                    } else {
                        $("#" + tableId).bootstrapTreeTable('refresh', []);
                    }
                }
            },
            // 获取选中复选框项
            selectCheckeds: function (name) {
                var checkeds = "";
                $('input:checkbox[name="' + name + '"]:checked').each(function (i) {
                    if (0 == i) {
                        checkeds = $(this).val();
                    } else {
                        checkeds += ("," + $(this).val());
                    }
                });
                return checkeds;
            },
            // 获取选中下拉框项
            selectSelects: function (name) {
                var selects = "";
                $('#' + name + ' option:selected').each(function (i) {
                    if (0 == i) {
                        selects = $(this).val();
                    } else {
                        selects += ("," + $(this).val());
                    }
                });
                return selects;
            },
            // 表单搜索
            search: function () {
                // 表单搜索回调函数
                if (typeof formSearchCallBlack == 'function') {
                    formSearchCallBlack();
                }
            },
            // 详情页无法编辑
            disabledForm: function (formId) {
                $("form[id='"+ formId +"'] :input").attr("readonly", true);
                $("form[id='"+ formId +"'] :text").attr('readonly', true);
                $("form[id='"+ formId +"'] textarea").attr("readonly", true);
                $("form[id='"+ formId +"'] select").attr("disabled", true);
                $("form[id='"+ formId +"'] :radio").attr("disabled", true);
                $("form[id='"+ formId +"'] :checkbox").attr("disabled", true);
            },
            parseParam: function(data) {
                var fomartData = {};
                for (var key in data) {
                    if (null != data[key] && typeof data[key] == "object") {
                        var index2 = 0;
                        console.log(data[key].length)
                        $.each(data[key], function (i, data2) {
                            for (var key2 in data2) {
                                if (null != data2[key2] && typeof data2[key2] == "object") {
                                    var index3 = 0;
                                    $.each(data2[key2], function (i, data3) {
                                        for (var key3 in data3) {
                                            fomartData[key + "[" + index2 + "]." + key2 + "[" + index3 + "]." + key3] = data3[key3];
                                        }
                                        index3++;
                                    });
                                } else {
                                    fomartData[key + "[" + index2 + "]." + key2] = data2[key2];
                                }
                            }
                            index2++;
                        });
                    } else {
                        fomartData[key] = data[key];
                    }
                }
                return fomartData;
            },
            // 表单清空
            clear: function (formId) {
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                $("#" + currentId)[0].reset();
                $("#" + currentId).find('select').find('option').attr('selected', false);
                $("#" + currentId).find('select').find('option[value=""]').attr('selected', true);
            },
        },
        // 弹出层封装处理
        modal: {
            // 消息提示
            msg: function (content, type) {
                if (type == undefined) {
                    type = "secondary";
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-modal-loading am-modal-no-btn" tabIndex="-1" id="'+id+'">'+
                    '    <div class="am-modal-dialog am-panel-hd am-panel-bd am-panel-default">'+
                    '        <div class="am-modal-bd am-panel-hd" style="font-size: 1.6rem;">'+
                    '           <i class="am-icon-twitch am-text-'+type+'">：'+ content +'  </i><span class="dots am-text-'+type+'"><span>.</span><span>.</span><span>.</span></span>'
                    '        </div>'+
                    '    </div>'+
                    '</div>';
                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function(){
                    $target.remove();
                });
                $target.modal({
                    relatedTarget: this,
                    closeViaDimmer: false,
                    dimmer: false
                });
                setTimeout(function () {
                    $target.modal('close');
                    $target.remove();
                }, 2000);
            },
            // 错误消息
            msgError: function (content) {
                $.modal.msg(content, modal_status.ERROR);
            },
            // 成功消息
            msgSuccess: function (content) {
                $.modal.msg(content, modal_status.SUCCESS);
            },
            // 警告消息
            msgWarning: function (content) {
                $.modal.msg(content, modal_status.WARNING);
            },

            // 确认窗体
            alert: function (content, type) {
                if (type == undefined) {
                    type = "secondary";
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-modal-alert" tabindex="-1" id="'+id+'">' +
                    '    <div class="am-modal-dialog am-modal-bd">' +
                    '       <div class="am-modal-hd"><i class="am-text-'+ type +' am-icon-info-circle am-icon-lg"></i></div>' +
                    '       <div class="am-modal-bd">' +
                    '           <div class="am-modal-alert-content" style="padding: 20px 10px;text-align: center">' +
                                    content +
                    '           </div>' +
                    '       </div>' +
                    '       <div class="am-modal-footer2">' +
                    '           <button id="am-modal-btn-confirm" type="button" class="am-btn am-btn-primary am-radius" style="width: 100%;height: 100%;" data-am-modal-confirm>确定</button>' +
                    '       </div>' +
                    '    </div>' +
                    '</div>';
                $("body").append(target);
                var $target = $("#"+id);
                $(document).on('keyup', function(e) {
                    if(e.which == 13) { // 检查按键是否是回车键
                        // 在这里执行你想要的操作
                        $("#am-modal-btn-confirm").trigger("click");
                    }
                });
                $target.modal({
                    relatedTarget: this,
                    closeViaDimmer: false,
                    dimmer: false,
                    onConfirm: function (options) {
                        $target.modal('close');
                        $target.remove();
                    }
                });
            },
            // 错误提示
            alertError: function (content) {
                $.modal.alert(content, modal_status.ERROR);
            },
            // 成功提示
            alertSuccess: function (content) {
                $.modal.alert(content, modal_status.SUCCESS);
            },
            // 警告提示
            alertWarning: function (content) {
                $.modal.alert(content, modal_status.WARNING);
            },

            // 确认窗体
            confirm: function (content, callBack) {
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-modal-confirm" tabindex="-1" id="'+id+'">' +
                    '        <div class="am-modal-dialog am-modal-bd">' +
                    '            <div class="am-modal-hd"><i class="am-text-warning am-icon-question-circle am-icon-lg"></i></div>' +
                    '            <div class="am-modal-bd" id="fw-confirm-content">' +
                    '                 <div class="am-modal-confirm-content" >' +
                                            content +
                    '                </div>' +
                    '            </div>' +
                    '            <div class="am-modal-footer2 am-btn-group">' +
                    '               <button id="fw-modal-confirm" type="button" class="am-btn am-btn-primary am-radius" style="width: calc(50% - 2px);height: 100%;" data-am-modal-confirm>确定</button>' +
                    '               <button id="fw-modal-cancel" type="button" class="am-btn am-btn-danger am-radius fw-btn-transparent-hover" style="width: calc(50% - 2px);height: 100%;margin-left: 2px!important;" data-am-modal-cancel>取消</button>' +
                    '            </div>' +
                    '        </div>' +
                    '    </div>';
                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function() {
                    $target.remove();
                });
                $('.am-modal-btn').mouseenter(function() {
                    $(".am-modal-btn").removeClass("fw-btn-transparent-hover");
                    $(this).addClass("fw-btn-transparent-hover");
                });
                $(document).on('keyup', function(e) {
                    if(e.which == 13) { // 检查按键是否是回车键
                        // 在这里执行你想要的操作
                        $("#fw-modal-cancel").trigger("click");
                    }
                });
                $target.modal({
                    target: '#my-popup',
                    relatedTarget: this,
                    closeViaDimmer: false,
                    dimmer: false,
                    onConfirm: function (options) {
                        callBack(true);
                        $target.modal('close');
                    },
                    onCancel: function () {
                        $target.modal('close');
                        return;
                    }
                });
            },
            // 提示窗体
            prompt: function (title, title2, placeholder, type, callBack, defaultEnterBtn, optionDatas, defaultSelected, placeholder2) {
                if(!defaultEnterBtn){
                    defaultEnterBtn = "confirm";
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-modal-prompt" tabindex="-1" id="'+id+'">' +
                    '  <div class="am-modal-dialog am-modal-bd">' +
                    '    <div class="am-modal-hd"><b>' + title + '</b></div>' +
                    '    <div class="am-modal-bd">';
                target += '<div class="prompt-form">';
                target += '    <span class="am-block" style="width: 100%;text-align: left;">'+title2+'</span>';
                $.each(type.split(","), function (index, item) {
                    if(item == 'text' || item == 'password' || item == 'hidden' || item == 'number') {
                        target += '      <input type="'+item+'" name="input_val" class="am-form-field" spellcheck=false autocomplete="off" placeholder="'+placeholder+'"/>';
                    }else if(item == 'select') {
                        target += '      <select class="am-form-field am-radius" name="configType" data-am-selected="{maxHeight: 100}">\n';
                        if($.isArray(optionDatas)) {
                            target += '            <option value="">-- 请选择 --</option>\n';
                            optionDatas.forEach(function (item, index) {
                                if(defaultSelected == item.dictValue) {
                                    target += '            <option value="'+item.dictValue+'" selected>'+item.dictLabel+'</option>\n';
                                }else {
                                    target += '            <option value="'+item.dictValue+'">'+item.dictLabel+'</option>\n';
                                }
                            });
                        }if(typeof optionDatas == 'string') {
                            target += optionDatas;
                        }
                        target += '     </select>';
                    }else if(item == 'textarea') {
                        target += '      <textarea class="am-form-field am-radius" name="remark" rows="3" placeholder="'+(placeholder2 || placeholder || '')+'"></textarea>';
                    }
                });
                target += '    </div>';
                target += '    </div>';
                if(defaultEnterBtn == "confirm"){
                    target +=
                        '    <div class="am-modal-footer2 am-btn-group">' +
                        // '      <span id="am-modal-prompt-btn-confirm" class="am-modal-btn am-btn-transparent fw-btn-transparent-hover" data-am-modal-confirm>提交</span>' +
                        // '      <span id="am-modal-prompt-btn-cancel" class="am-modal-btn am-btn-transparent" data-am-modal-cancel>取消</span>' +
                        '        <button id="am-modal-prompt-btn-confirm" type="button" class="am-btn am-btn-primary am-radius fw-btn-transparent-hover" style="width: calc(50% - 2px);height: 100%;" data-am-modal-confirm>确定</button>' +
                        '        <button id="am-modal-prompt-btn-cancel" type="button" class="am-btn am-btn-danger am-radius" style="width: calc(50% - 2px);height: 100%;margin-left: 2px!important;" data-am-modal-cancel>取消</button>' +
                        '    </div>';
                }else {
                    target +=
                        '    <div class="am-modal-footer2 am-btn-group">' +
                        '        <button id="am-modal-prompt-btn-confirm" type="button" class="am-btn am-btn-primary am-radius" style="width: calc(50% - 2px);height: 100%;" data-am-modal-confirm>确定</button>' +
                        '        <button id="am-modal-prompt-btn-cancel" type="button" class="am-btn am-btn-danger am-radius fw-btn-transparent-hover" style="width: calc(50% - 2px);height: 100%;margin-left: 2px!important;" data-am-modal-cancel>取消</button>' +
                        '    </div>';
                }
                target += '  </div>' +
                    '</div>';

                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function() {
                    $target.remove();
                });
                $('.am-modal-btn').mouseenter(function() {
                    $(".am-modal-btn").removeClass("fw-btn-transparent-hover");
                    $(this).addClass("fw-btn-transparent-hover");
                });
                $(document).on('keyup', function(e) {
                    if(e.which == 13) { // 检查按键是否是回车键
                        // 在这里执行你想要的操作
                        $(".am-modal-footer .fw-btn-transparent-hover").trigger("click");
                    }
                });
                $target.modal({
                    relatedTarget: this,
                    closeViaDimmer: false,
                    dimmer: false,
                    onConfirm: function(e) {
                        if(type == 'select') {
                            var $selected = $target.find('select option').filter(function(index) {
                                return this.selected;
                            });
                            callBack($selected);
                        }else if(type == 'textarea' ) {
                            var remark = $target.find('textarea').val();
                            callBack(remark);
                        }else if(type.indexOf('select')!=-1 && type.indexOf('textarea')!=-1 ) {
                            var $selected = $target.find('select option').filter(function(index) {
                                return this.selected;
                            });
                            var remark = $target.find('textarea').val();
                            callBack([$selected, remark]);
                        } else {
                            callBack(e.data);
                        }
                        $target.modal('close');
                        $target.remove();
                    },
                    onCancel: function(e) {
                        $target.modal('close');
                        $target.remove();
                        return true;
                    }
                });
                $("#"+id + " input").focus();
            },

            // 弹出层
            open: function (title, url, width, height, callback, hasBtn) {
                if ($.common.isMobile()) {
                    width = $(window).width();
                    height = $(window).height();
                }
                if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = ctx + "osfw/error/404";
                }
                if ($.common.isEmpty(width) || $(window).width() < width) {
                    width = ($(window).width() - 100);
                }
                if ($.common.isEmpty(height) || $(window).height() < height) {
                    height = ($(window).height() - 100);
                }
                if ($.common.isEmpty(hasBtn)) {
                    hasBtn = true;
                }
                if ($.common.isEmpty(callback)) {
                    callback = function (index, modalo) {
                        var iframeWin = modalo.find('iframe')[0];
                        iframeWin.contentWindow.submitHandler(index, modalo);
                    }
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-panel-default" tabIndex="-1" id="'+id+'">'+
                    '    <div class="am-modal-dialog">'+
                    '<a href="javascript: void(0)" class="am-close am-close-alt am-close-spin am-icon-times am-align-left am-margin-sm" style="margin-left: 20px;" title="关闭窗口" data-am-modal-close></a>' +
                    '<a href="javascript: void(0)" class="am-close am-close-alt am-close-spin am-icon-times am-align-right am-margin-sm" style="margin-right: 20px;" title="关闭窗口" data-am-modal-close></a>' +
                    (!title ? '' : '    <div class="am-modal-hd" style="height: 45px">' + title + '</div>')+
                    '        <div class="am-modal-bd" style="height: calc(100% - 94px)">'+
                    '            <iframe class="fw_iframe" name="'+id+'"  width="100%" height="100%" data-id="0" style="vertical-align:bottom;"' +
                    '                        src="' + url + '" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe>'+
                    '        </div>'+
                    '         <div class="am-modal-footer2">'+
                    (!hasBtn ? '' : '            <button type="button" class="am-btn am-btn-primary am-radius" style="width: 100%;height: 100%;" data-am-modal-confirm>确定</button>')+
                    '    </div>'+
                    '    </div>'+
                    '</div>';
                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function(){
                    $target.remove();
                });
                $target.modal({
                    relatedTarget: this,
                    closeViaDimmer: false,
                    dimmer:false,
                    width: width,
                    height: height,
                    onConfirm: function (options) {
                        callback(id, $target);
                    },
                    onCancel: function (options) {
                        $target.modal('close');
                        $target.remove();
                        return true;
                    }
                });
            },
            // 弹出层背景透明
            openTransparentFull: function (title, url, callback, hasBtn) {
                var width = $(window).width();
                var height = $(window).height();
                if ($.common.isMobile()) {
                    width = $(window).width();
                    height = $(window).height();
                }
                if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = ctx + "osfw/error/404";
                }
                if ($.common.isEmpty(hasBtn)) {
                    hasBtn = true;
                }
                if ($.common.isEmpty(callback)) {
                    callback = function (index, modalo) {
                        var iframeWin = modalo.find('iframe')[0];
                        iframeWin.contentWindow.submitHandler(index, modalo);
                    }
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-popup fw-popup" tabIndex="-1" id="'+id+'">'+
                    '       <img class="fw-close-img" src="'+ ctx +'osfw/framework/index/img/close.png" title="关闭窗口" data-am-modal-close />' +
                    '       <iframe class="fw_iframe" name="'+id+'"  width="100%" height="100%" data-id="0" style="vertical-align:bottom;"' +
                    '               src="' + url + '" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe>'+
                    '</div>';
                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function(){
                    $target.remove();
                });
                $target.on('open.modal.amui', function(){
                    setTimeout(function () {
                        $target.css('margin-left', (parseInt($target.css('margin-left').replace('px', '')) - 1) + "px");
                        $target.css('margin-top', (parseInt($target.css('margin-top').replace('px', '')) - 1) + "px");
                    }, 100);
                });
                $target.modal({
                    relatedTarget: this,
                    width: width,
                    height: height,
                    dimmer: false,
                    closeViaDimmer: false,
                    onConfirm:  function (options) {
                        callback(id, $target);
                    },
                    onCancel: function (options) {
                        $target.modal('close');
                        $target.remove();
                        return true;
                    }
                });
            },
            // 弹出层全屏
            openFull: function (title, url, callback, hasBtn) {
                var width = $(window).width();
                var height = $(window).height();
                if ($.common.isMobile()) {
                    width = $(window).width();
                    height = $(window).height();
                }
                if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = ctx + "osfw/error/404";
                }
                if ($.common.isEmpty(hasBtn)) {
                    hasBtn = true;
                }
                if ($.common.isEmpty(callback)) {
                    callback = function (index, modalo) {
                        var iframeWin = modalo.find('iframe')[0];
                        iframeWin.contentWindow.submitHandler(index, modalo);
                    }
                }
                var id = Date.now().toString(36);
                var target =
                    '<div class="am-modal am-panel-default" tabIndex="-1" id="'+id+'">'+
                    '    <div class="am-modal-dialog">'+
                    '<a href="javascript: void(0)" class="am-close am-close-alt am-close-spin am-icon-times am-align-left am-margin-sm" style="margin-left: 20px;" title="关闭窗口" data-am-modal-close></a>' +
                    '<a href="javascript: void(0)" class="am-close am-close-alt am-close-spin am-icon-times am-align-right am-margin-sm" style="margin-right: 20px;" title="关闭窗口" data-am-modal-close></a>' +
                    (!title ? '' : '    <div class="am-modal-hd" style="height: 45px">' + title + '</div>')+
                    '        <div class="am-modal-bd" style="height: calc(100% - 94px)">'+
                    '            <iframe class="fw_iframe" name="'+id+'"  width="100%" height="100%" data-id="0" style="vertical-align:bottom;"' +
                    '                        src="' + url + '" frameborder="0" scrolling="yes" marginheight="0" marginwidth="0"></iframe>'+
                    '        </div>'+
                    '         <div class="am-modal-footer2">'+
                    (!hasBtn ? '' : '            <button type="button" class="am-btn am-btn-primary am-radius" style="width: 100%;height: 100%;" data-am-modal-confirm>提交</button>')+
                    '    </div>'+
                    '    </div>'+
                    '</div>';
                $("body").append(target);
                var $target = $("#"+id);
                $target.on('closed.modal.amui', function(){
                    $target.remove();
                });
                $target.on('open.modal.amui', function(){
                    setTimeout(function () {
                        $target.css('margin-left', (parseInt($target.css('margin-left').replace('px', '')) - 1) + "px");
                        $target.css('margin-top', (parseInt($target.css('margin-top').replace('px', '')) - 1) + "px");
                    }, 100);
                });
                $target.modal({
                    relatedTarget: this,
                    width: width,
                    height: height,
                    dimmer: false,
                    closeViaDimmer: false,
                    onConfirm:  function (options) {
                        callback(id, $target);
                    },
                    onCancel: function (options) {
                        $target.modal('close');
                        $target.remove();
                        return true;
                    }
                });
            },
            // 选卡页方式打开
            openTab: function (menuId, title, icon, url) {
                parent.add_menu_tab(menuId, title, icon, url);
            },
            // 关闭窗体
            close: function (index) {
                if(index != undefined && index != null && index != ''){
                    $(document).find('#'+index).remove();
                }else {
                    $(window.frameElement).closest("#"+window.name).remove();
                }
            },
            // 关闭全部窗体
            closeAll: function () {
                $(window.parent.document).find(".am-modal").remove();
            },
            // 关闭选项卡
            closeTab: function (obj) {
                close_nav_tab(obj);
            },

            // 禁用按钮
            disable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $("*[class*=am-btn]", doc).addClass("am-disabled");
            },
            // 启用按钮
            enable: function() {
                var doc = window.top == window.parent ? window.document : window.parent.document;
                $("*[class*=am-btn]", doc).removeClass("am-disabled");
            },

            // 打开遮罩层
            loading: function (message) {
                // $.blockUI({ message: '<div class="loaderbox"><div class="loading-activity"></div> ' + message + '</div>' });
            },
            // 关闭遮罩层
            closeLoading: function () {
                // setTimeout(function(){
                //     $.unblockUI();
                // }, 50);
            },

            // 重新加载
            reload: function () {
                parent.location.reload();
            }
        },
        // 操作封装处理
        operate: {
            // 提交数据
            submit: function(url, type, dataType, data, callback, notSafeCallback) {
                var config = {
                    url: url,
                    type: type,
                    dataType: dataType,
                    // contentType: "application/json;charset=utf-8",
                    data: data,
                    json: 'callback',
                    async: true,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍候...");
                    },
                    success: function (result) {
                        $.modal.closeLoading();
                        if (result.code == web_status.SUCCESS) {
                            if(typeof callback == "function"){
                                callback(result);
                            }else {
                                $.operate.ajaxSuccess(result);
                            }
                        } else if (result.code == web_status.WARNING) { // 执行异常情况
                            $.modal.alertWarning(result.msg);
                        } else if (result.code == web_status.UNSAFE) { // 需要二级认证
                            $.validate.openSafe(notSafeCallback);
                        } else { // 执行异常情况
                            $.modal.alertError(result.msg);
                        }
                    },
                    error: function (xhr, status, error) {
                        var errorMessage = "请求失败，请稍后再试。";
                        if (xhr.status === 0) {
                            errorMessage = "网络连接失败，请检查网络设置。";
                        } else if (xhr.status === 404) {
                            errorMessage = "请求的资源不存在。";
                        } else if (xhr.status === 500) {
                            var responseText = JSON.parse(xhr.responseText);
                            errorMessage = responseText.msg;
                        } else if (error === "timeout") {
                            errorMessage = "请求超时，请稍后再试。";
                        }
                        // 显示错误提示给用户
                        $.modal.alertError(errorMessage);
                    }
                };
                $.ajax(config)
            },
            // post请求传输
            post: function(url, data, callback, notSafeCallback) {
                $.operate.submit(url, "post", "json", data, callback, notSafeCallback);
            },
            // get请求传输
            get: function(url, callback, notSafeCallback) {
                $.operate.submit(url, "get", "json", "", callback, notSafeCallback);
            },

            // 详细信息
            detail: function(id, width, height) {
                table.set();
                var _url = $.operate.detailUrl(id);
                var _title = "详细" + table.options.modalName;
                $.modal.open(_title, _url, width, height, null, false);
            },
            // 详细信息
            detailFull: function(id) {
                table.set();
                var _url = $.operate.detailUrl(id);
                var _title = "详细" + table.options.modalName;
                $.modal.openFull(_title, _url, null, false);
            },
            // 详细信息，以tab页展现
            detailTab: function(id) {
                table.set();
                var _url = $.operate.detailUrl(id);
                var _title = "详细" + table.options.modalName;
                $.modal.openTab(id, _title, null, _url);
            },
            // 详细访问地址
            detailUrl: function(id) {
                var url = "/404.html";
                if ($.common.isNotEmpty(id)) {
                    url = table.options.detailUrl.replace("{id}", id);
                } else {
                    var id = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                    if (id.length == 0) {
                        $.modal.alertWarning("请至少选择一条记录");
                        return;
                    }
                    url = table.options.detailUrl.replace("{id}", id);
                }
                return url;
            },

            // 删除信息
            remove: function(id, modal) {
                table.set();
                if(modal == "prompt") {
                    $.modal.prompt("确定删除该条" + table.options.modalName + "信息吗？", "请输入您要删除的理由：", "", "textarea", function (data) {
                        var url = $.common.isEmpty(id) ? table.options.removeUrl : table.options.removeUrl.replace("{id}", id);
                        if(table.options.type == table_type.bootstrapTreeTable) {
                            var data = { "deleteReason": data || '' };
                            $.operate.submit(url, "get", "json", data);
                        } else {
                            var data = { "ids": id, "deleteReason": data || '' };
                            $.operate.submit(url, "post", "json", data);
                        }
                    });
                }else {
                    $.modal.confirm("确定删除该条" + table.options.modalName + "信息吗？", function() {
                        var url = $.common.isEmpty(id) ? table.options.removeUrl : table.options.removeUrl.replace("{id}", id);
                        if(table.options.type == table_type.bootstrapTreeTable) {
                            $.operate.get(url);
                        } else {
                            var data = { "ids": id };
                            $.operate.submit(url, "post", "json", data);
                        }
                    });
                }
            },
            // 批量删除信息
            removeAll: function(modal) {
                table.set();
                var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                if (rows.length == 0) {
                    $.modal.alertWarning("请至少选择一条记录");
                    return;
                }
                if(modal == "prompt") {
                    $.modal.prompt("确认要删除选中的" + rows.length + "条数据吗?", "请输入您要删除的理由：", "", "textarea", function (data) {
                        var url = table.options.removeUrl;
                        var data = { "ids": rows.join(), "deleteReason": data || '' };
                        $.operate.submit(url, "post", "json", data);
                    });
                }else {
                    $.modal.confirm("确认要删除选中的" + rows.length + "条数据吗?", function() {
                        var url = table.options.removeUrl;
                        var data = { "ids": rows.join() };
                        $.operate.submit(url, "post", "json", data);
                    });
                }
            },
            // 清空信息
            clean: function() {
                table.set();
                $.modal.confirm("确定清空所有" + table.options.modalName + "吗？", function() {
                    var url = table.options.cleanUrl;
                    $.operate.submit(url, "post", "json", "");
                });
            },

            // 添加信息
            add: function(id, width, height) {
                table.set();
                var _title = "添加" + table.options.modalName;
                var _url =  $.operate.addUrl(id);
                $.modal.open(_title, _url, width, height);
            },
            // 添加信息 全屏
            addFull: function(id) {
                table.set();
                var _title = "添加" + table.options.modalName;
                var _url =  $.operate.addUrl(id);
                $.modal.openFull(_title, _url);
            },
            // 添加信息，以tab页展现
            addTab: function (id) {
                table.set();
                var _title = "添加" + table.options.modalName;
                var _url =  $.operate.addUrl(id);
                $.modal.openTab(id, _title, null, _url);
            },
            // 添加访问地址
            addUrl: function(id) {
                var url = $.common.isEmpty(id) ? table.options.createUrl.replace("{id}", "") : table.options.createUrl.replace("{id}", id);
                return url;
            },

            // 修改信息
            edit: function(id, width, height) {
                table.set();
                var _title = "修改" + table.options.modalName;
                if($.common.isEmpty(id) && table.options.type == table_type.bootstrapTreeTable) {
                    var row = $("#" + table.options.id).bootstrapTreeTable('getSelections')[0];
                    if ($.common.isEmpty(row)) {
                        $.modal.alertWarning("请至少选择一条记录");
                        return;
                    }
                    var _url = table.options.updateUrl.replace("{id}", row[table.options.uniqueId]);
                    $.modal.open(_title, _url, width, height);
                } else {
                    var _url = $.operate.editUrl(id);
                    $.modal.open(_title, _url, width, height);
                }
            },
            // 修改信息 全屏
            editFull: function(id) {
                table.set();
                var url = "/404.html";
                var _title = "修改" + table.options.modalName;
                if ($.common.isNotEmpty(id)) {
                    url = table.options.updateUrl.replace("{id}", id);
                } else {
                    if(table.options.type == table_type.bootstrapTreeTable) {
                        var row = $("#" + table.options.id).bootstrapTreeTable('getSelections')[0];
                        if ($.common.isEmpty(row)) {
                            $.modal.alertWarning("请至少选择一条记录");
                            return;
                        }
                        url = table.options.updateUrl.replace("{id}", row[table.options.uniqueId]);
                    } else {
                        var row = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                        url = table.options.updateUrl.replace("{id}", row);
                    }
                }
                $.modal.openFull(_title, url);
            },
            // 修改信息，以tab页展现
            editTab: function(id) {
                table.set();
                var _title = "修改" + table.options.modalName;
                var _url = $.operate.editUrl(id);
                $.modal.openTab(id, _title, null, _url);
            },
            // 修改访问地址
            editUrl: function(id) {
                var url = "/404.html";
                if ($.common.isNotEmpty(id)) {
                    url = table.options.updateUrl.replace("{id}", id);
                } else {
                    var id = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
                    if (id.length == 0) {
                        $.modal.alertWarning("请至少选择一条记录");
                        return;
                    }
                    url = table.options.updateUrl.replace("{id}", id);
                }
                return url;
            },

            // 保存信息 刷新表格
            save: function(url, data, callback) {
                var config = {
                    url: url,
                    type: "post",
                    dataType: "json",
                    data: data,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍候...");
                    },
                    success: function(result) {
                        if (typeof callback == "function") {
                            callback(result);
                        }
                        $.operate.successCallback(result);
                    }
                };
                $.ajax(config)
            },
            // 保存信息 弹出结果提示框
            saveModal: function(url, data, callback) {
                var config = {
                    url: url,
                    type: "post",
                    dataType: "json",
                    data: data,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍候...");
                    },
                    success: function(result) {
                        if (typeof callback == "function") {
                            callback(result);
                        }
                        if (result.code == web_status.SUCCESS) {
                            $.modal.alertSuccess(result.msg)
                        } else if (result.code == web_status.WARNING) {
                            $.modal.alertWarning(result.msg)
                        } else {
                            $.modal.alertError(result.msg);
                        }
                        $.modal.closeLoading();
                    }
                };
                $.ajax(config)
            },
            // 保存选项卡信息
            saveTab: function(url, data, callback) {
                var config = {
                    url: url,
                    type: "post",
                    dataType: "json",
                    data: data,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍候...");
                    },
                    success: function(result) {
                        if (typeof callback == "function") {
                            callback(result);
                        }
                        $.operate.successTabCallback(result);
                    }
                };
                $.ajax(config)
            },

            // 保存结果弹出msg刷新table表格
            ajaxSuccess: function (result) {
                if (result.code == web_status.SUCCESS && table.options.type == table_type.bootstrapTable) {
                    $.modal.msgSuccess(result.msg);
                    $.table.refresh();
                } else if (result.code == web_status.SUCCESS && table.options.type == table_type.bootstrapTreeTable) {
                    $.modal.msgSuccess(result.msg);
                    $.treeTable.refresh();
                } else if (result.code == web_status.SUCCESS && table.option.type == undefined) {
                    $.modal.msgSuccess(result.msg)
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else if (result.code == web_status.REPEAT) {
                    $.modal.alertWarning(result.msg);
                    // 禁用按钮
                    $.modal.disable();
                    setTimeout(function () {
                        // 启用按钮
                        $.modal.enable();
                    }, 10000);
                } else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            },
            // 成功回调执行事件（父窗体静默更新）
            successCallback: function (result) {
                if (result.code == web_status.SUCCESS) {
                    var parent = window.parent;
                    if (parent.table.options.type == table_type.bootstrapTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.table.refresh();
                    } else if (parent.table.options.type == table_type.bootstrapTreeTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.treeTable.refresh();
                    } else {
                        $.modal.msgReload("保存成功,正在刷新数据请稍后……", modal_status.SUCCESS);
                    }
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg);
                } else if (result.code == web_status.REPEAT) {
                    $.modal.alertWarning(result.msg);
                    // 禁用按钮
                    $.modal.disable();
                    setTimeout(function () {
                        // 启用按钮
                        $.modal.enable();
                    }, 10000);
                } else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
                $.modal.enable();
            },
            // 选项卡成功回调执行事件（父窗体静默更新）
            successTabCallback: function(result) {
                if (result.code == web_status.SUCCESS) {
                    var topWindow = $(window.parent.document);
                    var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-panel');
                    var $contentWindow = $('.iframe[data-id="' + currentId + '"]', topWindow)[0].contentWindow;
                    $.modal.close();
                    $contentWindow.$.modal.msgSuccess(result.msg);
                    $contentWindow.$(".layui-layer-padding").removeAttr("style");
                    if ($contentWindow.table.options.type == table_type.bootstrapTable) {
                        $contentWindow.$.table.refresh();
                    } else if ($contentWindow.table.options.type == table_type.bootstrapTreeTable) {
                        $contentWindow.$.treeTable.refresh();
                    }
                    $.modal.closeTab();
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else if (result.code == web_status.REPEAT) {
                    $.modal.alertWarning(result.msg);
                    // 禁用按钮
                    $.modal.disable();
                    setTimeout(function () {
                        // 启用按钮
                        $.modal.enable();
                    }, 10000);
                }  else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            }
        },
        // 校验封装处理
        validate: {
            openSafe: function (callback) {
                $.modal.prompt("这里需要再次确认您的身份", "请输入您的密码：（有效时间2分钟）", "请输入您的密码", "password", function (data) {
                    $.ajax({
                        type: "post",
                        url: ctx + "osfw/openSafe",
                        data: {
                            "password": sm2.doEncrypt(data, parent.publicKey),
                        },
                        async: true,
                        success: function (res) {
                            if (res.code == web_status.SUCCESS) {
                                $.modal.msgSuccess(res.msg);
                                if (typeof callback == "function") {
                                    callback(res);
                                }
                            } else {
                                $.modal.alertError(res.msg);
                            }
                        }
                    });
                });
            },
            // 判断返回标识是否唯一
            unique: function (value) {
                if (value === true || value === "true" || value === 0 || value === "0") {
                    return true;
                }
                return false;
            },
            // 表单验证
            form: function (formId) {
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                return $("#" + currentId).validate().form();
            },
            // 重置表单验证（清除提示信息）
            reset: function (formId) {
                var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
                return $("#" + currentId).validate().resetForm();
            }
        },
        // 树插件封装处理
        tree: {
            _option: {},
            _lastValue: {},
            // 初始化树结构
            init: function(options) {
                var defaults = {
                    id: "tree",                    // 属性ID
                    expandLevel: 0,                // 展开等级节点
                    view: {
                        selectedMulti: false,      // 设置是否允许同时选中多个节点
                        nameIsHTML: true           // 设置 name 属性是否支持 HTML 脚本
                    },
                    check: {
                        enable: false,             // 置 zTree 的节点上是否显示 checkbox / radio
                        nocheckInherit: true,      // 设置子节点是否自动继承
                        chkboxType: { "Y": "ps", "N": "ps" } // 父子节点的关联关系
                    },
                    data: {
                        key: {
                            title: "title"         // 节点数据保存节点提示信息的属性名称
                        },
                        simpleData: {
                            enable: true           // true / false 分别表示 使用 / 不使用 简单数据模式
                        }
                    },
                };
                var options = $.extend(defaults, options);
                $.tree._option = options;
                // 树结构初始化加载
                var setting = {
                    callback: {
                        onClick: options.onClick,                      // 用于捕获节点被点击的事件回调函数
                        onCheck: options.onCheck,                      // 用于捕获 checkbox / radio 被勾选 或 取消勾选的事件回调函数
                        onDblClick: options.onDblClick                 // 用于捕获鼠标双击之后的事件回调函数
                    },
                    check: options.check,
                    view: options.view,
                    data: options.data
                };
                $.get(options.url, function(data) {
                    var treeId = $("#treeId").val();
                    tree = $.fn.zTree.init($("#" + options.id), setting, data);
                    $._tree = tree;
                    for (var i = 0; i < options.expandLevel; i++) {
                        var nodes = tree.getNodesByParam("level", i);
                        for (var j = 0; j < nodes.length; j++) {
                            tree.expandNode(nodes[j], true, false, false);
                        }
                    }
                    var node = tree.getNodesByParam("id", treeId, null)[0];
                    $.tree.selectByIdName(treeId, node);
                    // 回调tree方法
                    if(typeof(options.callBack) === "function"){
                        options.callBack(tree);
                    }
                });
            },
            // 搜索节点
            searchNode: function() {
                // 取得输入的关键字的值
                var value = $.common.trim($("#keyword").val());
                if ($.tree._lastValue == value) {
                    return;
                }
                // 保存最后一次搜索名称
                $.tree._lastValue = value;
                var nodes = $._tree.getNodes();
                // 如果要查空字串，就退出不查了。
                if (value == "") {
                    $.tree.showAllNode(nodes);
                    return;
                }
                $.tree.hideAllNode(nodes);
                // 根据搜索值模糊匹配
                $.tree.updateNodes($._tree.getNodesByParamFuzzy("name", value));
            },
            // 根据Id和Name选中指定节点
            selectByIdName: function(treeId, node) {
                if ($.common.isNotEmpty(treeId) && node && treeId == node.id) {
                    $._tree.selectNode(node, true);
                }
            },
            // 显示所有节点
            showAllNode: function(nodes) {
                nodes = $._tree.transformToArray(nodes);
                for (var i = nodes.length - 1; i >= 0; i--) {
                    if (nodes[i].getParentNode() != null) {
                        $._tree.expandNode(nodes[i], true, false, false, false);
                    } else {
                        $._tree.expandNode(nodes[i], true, true, false, false);
                    }
                    $._tree.showNode(nodes[i]);
                    $.tree.showAllNode(nodes[i].children);
                }
            },
            // 隐藏所有节点
            hideAllNode: function(nodes) {
                var nodes = $._tree.transformToArray(nodes);
                for (var i = nodes.length - 1; i >= 0; i--) {
                    $._tree.hideNode(nodes[i]);
                }
            },
            // 显示所有父节点
            showParent: function(treeNode) {
                var parentNode;
                while ((parentNode = treeNode.getParentNode()) != null) {
                    $._tree.showNode(parentNode);
                    $._tree.expandNode(parentNode, true, false, false);
                    treeNode = parentNode;
                }
            },
            // 显示所有孩子节点
            showChildren: function(treeNode) {
                if (treeNode.isParent) {
                    for (var idx in treeNode.children) {
                        var node = treeNode.children[idx];
                        $._tree.showNode(node);
                        $.tree.showChildren(node);
                    }
                }
            },
            // 更新节点状态
            updateNodes: function(nodeList) {
                $._tree.showNodes(nodeList);
                for (var i = 0, l = nodeList.length; i < l; i++) {
                    var treeNode = nodeList[i];
                    $.tree.showChildren(treeNode);
                    $.tree.showParent(treeNode)
                }
            },
            // 获取当前被勾选集合
            getCheckedNodes: function(column) {
                var _column = $.common.isEmpty(column) ? "id" : column;
                var nodes = $._tree.getCheckedNodes(true);
                return $.map(nodes, function (row) {
                    return row[_column];
                }).join();
            },
            // 不允许根父节点选择
            notAllowParents: function(_tree) {
                var nodes = _tree.getSelectedNodes();
                if(nodes.length == 0){
                    $.modal.msgError("请选择节点后提交");
                    return false;
                }
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].level == 0) {
                        $.modal.msgError("不能选择根节点（" + nodes[i].name + "）");
                        return false;
                    }
                    if (nodes[i].isParent) {
                        $.modal.msgError("不能选择父节点（" + nodes[i].name + "）");
                        return false;
                    }
                }
                return true;
            },
            // 不允许最后层级节点选择
            notAllowLastLevel: function(_tree) {
                var nodes = _tree.getSelectedNodes();
                for (var i = 0; i < nodes.length; i++) {
                    if (!nodes[i].isParent) {
                        $.modal.msgError("不能选择最后层级节点（" + nodes[i].name + "）");
                        return false;
                    }
                }
                return true;
            },
            // 隐藏/显示搜索栏
            toggleSearch: function() {
                $('#search').slideToggle(200);
                $('#btnShow').toggle();
                $('#btnHide').toggle();
                $('#keyword').focus();
            },
            // 折叠
            collapse: function() {
                $._tree.expandAll(false);
            },
            // 展开
            expand: function() {
                $._tree.expandAll(true);
            }
        },
        // 通用方法封装处理
        common: {
            // 判断字符串是否为空
            isEmpty: function (value) {
                if (value == undefined || value == null || this.trim(value) == "") {
                    return true;
                }
                return false;
            },
            // 判断一个字符串是否为非空串
            isNotEmpty: function (value) {
                return !$.common.isEmpty(value);
            },
            // 空对象转字符串
            nullToStr: function(value) {
                if ($.common.isEmpty(value)) {
                    return "-";
                }
                return value;
            },
            // 是否显示数据 为空默认为显示
            visible: function (value) {
                if ($.common.isEmpty(value) || value == true) {
                    return true;
                }
                return false;
            },
            // 空格截取
            trim: function (value) {
                if (value == null) {
                    return "";
                }
                return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
            },
            // 比较两个字符串（大小写敏感）
            equals: function (str, that) {
                return str == that;
            },
            // 比较两个字符串（大小写不敏感）
            equalsIgnoreCase: function (str, that) {
                return String(str).toUpperCase() === String(that).toUpperCase();
            },
            // 将字符串按指定字符分割
            split: function (str, sep, maxLen) {
                if ($.common.isEmpty(str)) {
                    return null;
                }
                var value = String(str).split(sep);
                return maxLen ? value.slice(0, maxLen - 1) : value;
            },
            // 字符串格式化(%s )
            sprintf: function (str) {
                var args = arguments, flag = true, i = 1;
                str = str.replace(/%s/g, function () {
                    var arg = args[i++];
                    if (typeof arg === 'undefined') {
                        flag = false;
                        return '';
                    }
                    return arg == null ? '' : arg;
                });
                return flag ? str : '';
            },
            // 日期格式化 时间戳  -> yyyy-MM-dd HH-mm-ss
            dateFormat: function(date, format) {
                var that = this;
                if (that.isEmpty(date)) return "";
                if (!date) return;
                if (!format) format = "yyyy-MM-dd";
                switch (typeof date) {
                    case "string":
                        date = new Date(date.replace(/-/g, "/"));
                        break;
                    case "number":
                        date = new Date(date);
                        break;
                }
                if (!date instanceof Date) return;
                var dict = {
                    "yyyy": date.getFullYear(),
                    "M": date.getMonth() + 1,
                    "d": date.getDate(),
                    "H": date.getHours(),
                    "m": date.getMinutes(),
                    "s": date.getSeconds(),
                    "MM": ("" + (date.getMonth() + 101)).substr(1),
                    "dd": ("" + (date.getDate() + 100)).substr(1),
                    "HH": ("" + (date.getHours() + 100)).substr(1),
                    "mm": ("" + (date.getMinutes() + 100)).substr(1),
                    "ss": ("" + (date.getSeconds() + 100)).substr(1)
                };
                return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g,
                    function() {
                        return dict[arguments[0]];
                    });
            },
            // 获取节点数据，支持多层级访问
            getItemField: function (item, field) {
                var value = item;
                if (typeof field !== 'string' || item.hasOwnProperty(field)) {
                    return item[field];
                }
                var props = field.split('.');
                for (var p in props) {
                    value = value && value[props[p]];
                }
                return value;
            },
            // 指定随机数返回
            random: function (min, max) {
                return Math.floor((Math.random() * max) + min);
            },
            // 判断字符串是否是以start开头
            startWith: function(value, start) {
                var reg = new RegExp("^" + start);
                return reg.test(value)
            },
            // 判断字符串是否是以end结尾
            endWith: function(value, end) {
                var reg = new RegExp(end + "$");
                return reg.test(value)
            },
            // 数组去重
            uniqueFn: function(array) {
                var result = [];
                var hashObj = {};
                for (var i = 0; i < array.length; i++) {
                    if (!hashObj[array[i]]) {
                        hashObj[array[i]] = true;
                        result.push(array[i]);
                    }
                }
                return result;
            },
            // 数组中的所有元素放入一个字符串
            join: function(array, separator) {
                if ($.common.isEmpty(array)) {
                    return null;
                }
                return array.join(separator);
            },
            // 获取form下所有的字段并转换为json对象
            formToJSON: function(formId) {
                var json = {};
                $.each($("#" + formId).serializeArray(), function(i, field) {
                    if(json[field.name]) {
                        json[field.name] += ("," + field.value);
                    } else {
                        json[field.name] = field.value;
                    }
                });
                return json;
            },
            // 数据字典转下拉框
            dictToSelect: function(datas, value, name) {
                var actions = [];
                actions.push($.common.sprintf("<select class='form-control' name='%s'>", name));
                $.each(datas, function(index, dict) {
                    actions.push($.common.sprintf("<option value='%s'", dict.dictValue));
                    if (dict.dictValue == ('' + value)) {
                        actions.push(' selected');
                    }
                    actions.push($.common.sprintf(">%s</option>", dict.dictLabel));
                });
                actions.push('</select>');
                return actions.join('');
            },
            // 获取obj对象长度
            getLength: function(obj) {
                var count = 0;
                for (var i in obj) {
                    if (obj.hasOwnProperty(i)) {
                        count++;
                    }
                }
                return count;
            },
            // 判断移动端
            isMobile: function () {
                return navigator.userAgent.match(/(Android|iPhone|SymbianOS|Windows Phone|iPad|iPod)/i);
            },
            // 数字正则表达式，只能为0-9数字
            numValid : function(text){
                var patten = new RegExp(/^[0-9]+$/);
                return patten.test(text);
            },
            // 英文正则表达式，只能为a-z和A-Z字母
            enValid : function(text){
                var patten = new RegExp(/^[a-zA-Z]+$/);
                return patten.test(text);
            },
            // 英文、数字正则表达式，必须包含（字母，数字）
            enNumValid : function(text){
                var patten = new RegExp(/^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]+$/);
                return patten.test(text);
            },
            // 英文、数字、特殊字符正则表达式，必须包含（字母，数字，特殊字符!@#$%^&*()-=_+）
            charValid : function(text) {
                var patten = new RegExp(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[~!@#\$%\^&\*\(\)\-=_\+])[A-Za-z\d~!@#\$%\^&\*\(\)\-=_\+]{6,}$/);
                return patten.test(text);
            },
            // 中文正则表达式，必须包含（中文）
            chineseValid : function(text) {
                var patten = new RegExp(/[^\u4E00-\u9FA0]+$/);
                return !patten.test(text);
            },
            // 复制文本到粘贴板
            copyToClipboard: function (text) {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                // 防止元素显示在屏幕上
                textArea.style.position = "fixed";
                textArea.style.top = "0";
                textArea.style.left = "0";
                textArea.style.width = "2em";
                textArea.style.height = "2em";
                textArea.style.padding = "0";
                textArea.style.border = "none";
                textArea.style.outline = "none";
                textArea.style.boxShadow = "none";
                textArea.style.background = "transparent";
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    var successful = document.execCommand('copy');
                } catch (err) {
                    console.error('Oops, unable to copy', err);
                }
                document.body.removeChild(textArea);
                $.modal.msgSuccess("当前内容已复制");
            },
            // 文本框获取焦点后内容滚动到末尾
            setCssScrollEnd: function (element) {
                var sr = element;
                var range, selection;
                if (document.createRange) {
                    //Firefox, Chrome, Opera, Safari, IE 9+
                    range = document.createRange();//Create a range (a range is a like the selection but invisible)
                    range.selectNodeContents(element);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    selection = window.getSelection();//get the selection object (allows you to change selection)
                    selection.removeAllRanges();//remove any selections already made
                    selection.addRange(range);//make the range you have just created the visible selection
                } else if (document.selection) {
                    //IE 8 and lower
                    range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                    range.moveToElementText(element);//Select the entire contents of the element with the range
                    range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                    range.select();//Select the range (make it the visible selection
                }
                sr.scrollLeft = sr.scrollWidth;   // 内容滚动到最后一行
            },
            // 文本框双击全选文本
            dbClickSelectText: function (element) {
                if (!element) return
                var selection = window.getSelection();
                var range = document.createRange();
                range.selectNodeContents(element);
                selection.removeAllRanges();
                selection.addRange(range);
            },
            // 清除已框选的文本
            clearSelection: function () {
                if (window.getSelection) {
                    window.getSelection().removeAllRanges();
                } else if (document.selection) {
                    document.selection.empty();
                }
            },
        }
    });


    // select2复选框事件绑定
    if ($.fn.select2 !== undefined) {
        $.fn.select2.defaults.set("theme", "bootstrap");
        $("select:not(.noselect2)").each(function () {
            $(this).select2().on("change", function () {
                $(this).valid();
            })
        })
    }

    setSelect2Config();
})(jQuery);


/**********************************************************************************************************************/

/** 表格类型 */
table_type = {
    bootstrapTable: 0,
    bootstrapTreeTable: 1
};

/** 消息状态码 */
web_status = {
    SUCCESS: 0,
    WARNING: 301,
    UNSAFE: 412,
    ERROR: 500,
    REPEAT: 600
}

/** 弹窗状态码 */
modal_status = {
    SUCCESS: "success",
    ERROR: "danger",
    WARNING: "warning"
};


sql_oper_type = {
    EXECUTE: "execute",
    EXPLAIN: "explain",
    EXPORT: "export",
    STOP: "stop"
};



/**********************************************************************************************************************/


//表单数据转json数据
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [ o[this.name] ];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

//本地缓存处理
var storage = {
    set: function (key, value) {
        window.localStorage.setItem(key, value);
    },
    get: function (key) {
        return window.localStorage.getItem(key);
    },
    remove: function (key) {
        window.localStorage.removeItem(key);
    },
    clear: function () {
        window.localStorage.clear();
    }
};

/*// 原始的send方法
var originalSend = XMLHttpRequest.prototype.send;
// 重写send方法
XMLHttpRequest.prototype.send = function(data) {
    // 在发送请求前设置自定义的请求头
    if(storage.get("api-key")!=null && storage.get("api-token") != null) {
        this.setRequestHeader(storage.get("api-key"), null);
        this.setRequestHeader(storage.get("api-key"), storage.get("api-token"));
    }
    console.log(this.getResponseHeader("token"));
    // 调用原始的send方法
    try {
        originalSend.call(this, data);
    } catch (error) {
        throw error;
    }
};
// 保存原始的open方法
var origOpen = XMLHttpRequest.prototype.open;
// 重写open方法
XMLHttpRequest.prototype.open = function(method, url, async) {
    // 修改请求的URL
    if(url.includes('osfw/dwr/call')) {
        url = ctx + url.substring(url.indexOf('osfw/dwr/call'));
    }
    // 调用原始的open方法，并传入修改后的URL和其他参数
    origOpen.call(this, method, url, async);
};*/


/**********************************************************************************************************************/



/**
 * 同步阻塞
 *
 * @param milliseconds 阻塞毫秒数
 */
function sleep(milliseconds) {
    var start = new Date().getTime();
    while (true) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function divScroll(className){
    // 监听屏幕滚动，显示平滑滚动悬浮按钮
    $('.'+className).scroll(function (e){
        const scrollTop = $(this).scrollTop() - 100;
        scrollTop > 10 ? $("#fw-toolbar-goup").removeClass("am-hide") : $("#fw-toolbar-goup").addClass("am-hide");
        scrollTop > 10 ? $("#fw-toolbar-godown").addClass("am-hide") : $("#fw-toolbar-godown").removeClass("am-hide");
    });
    // 监听直达底部悬浮按钮点击，滑动至页面底部
    $('#fw-toolbar-godown').on('click', function() {
        var $w = $("."+className);
        $w.smoothScroll({position: $(document).height() - $w.height() + 100});
    });
    // 监听直达底部悬浮按钮点击，滑动至页面顶部
    $('#fw-toolbar-goup').on('click', function() {
        var $w = $("."+className);
        $w.smoothScroll({position:  - $w.scrollTop()});
    });

}

function jianshezhong() {
    $.modal.msgWarning("该功能正在努力建设中，敬请期待");
}

/* 设置select2组件参数 */
function setSelect2Config() {
    if($("select[tags]").length > 0){
        $.each($("select[tags]"), function(i, n){
            var tags = $(this).attr("tags") == 'true' ? true : false;
            $(this).select2({
                tags: tags
            });
        });
    }
    if($("select[closeOnSelect]").length > 0){
        $.each($("select[closeOnSelect]"), function(i, n){
            var closeOnSelect = $(this).attr("closeOnSelect") == 'false' ? false : true;
            $(this).select2({
                closeOnSelect: closeOnSelect
            });
        });
    }
}


//定义serializeObject方法，序列化表单
$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [ o[this.name] ];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


function parseParam(data) {
    var fomartData = {};
    for(var key in data){
        if(null != data[key] && typeof data[key] == "object"){
            var index2 = 0;
            console.log(data[key].length)
            $.each(data[key], function(i, data2){
                for(var key2 in data2){
                    if(null != data2[key2] && typeof data2[key2] == "object") {
                        var index3 = 0;
                        $.each(data2[key2], function (i, data3) {
                            for (var key3 in data3) {
                                fomartData[key + "[" + index2 + "]." + key2 + "[" + index3 + "]." + key3] = data3[key3];
                            }
                            index3++;
                        });
                    }else {
                        fomartData[key + "[" + index2 + "]." + key2] = data2[key2];
                    }
                }
                index2++;
            });
        }else {
            fomartData[key] = data[key];
        }
    }
    return fomartData;
}

function initLayoutLeft(auto) {
    if(auto){
        if ($(this).width() < 1000) {
            leftPanelIndent();
        }else {
            $(".fw-layout-left").next().removeClass("fw-layout-left-container-extension");
            $(".fw-layout-left").next().addClass("fw-layout-left-container-shrink");
        }
    }else {
        leftPanelIndent();
    }

    // 操作栏-展开/折叠
    $('#tree-foldbar-outdent').on('click', function () {
        leftPanelOutdent();
    });
    $('#tree-foldbar-indent').on('click', function () {
        leftPanelIndent();
    });
    // 操作栏-展开/折叠
    function leftPanelOutdent() {
        $(".fw-layout-left").next().removeClass("fw-layout-left-container-extension");
        $(".fw-layout-left").next().addClass("fw-layout-left-container-shrink");
        $(".fw-layout-left").removeClass("fw-layout-left-indent");
        $(".fw-layout-left").addClass("fw-layout-left-outdent");
        $(".fw-layout-left .panel-header, .fw-layout-left .panel-wrapper").removeClass("am-hide");
        $(".fw-layout-left .foldbar-outdent").addClass("am-hide");
        $('.fw-layout-left .foldbar-indent').removeClass("am-hide");
    }
    function leftPanelIndent() {
        $(".fw-layout-left").next().removeClass("fw-layout-left-container-shrink");
        $(".fw-layout-left").next().addClass("fw-layout-left-container-extension");
        $(".fw-layout-left .panel-header, .fw-layout-left .panel-wrapper").addClass("am-hide");
        $(".fw-layout-left").removeClass("fw-layout-left-outdent");
        $(".fw-layout-left").addClass("fw-layout-left-indent");
        $(".fw-layout-left .foldbar-outdent").removeClass("am-hide");
        $('.fw-layout-left .foldbar-indent').addClass("am-hide");
    }
}
function initLayoutRight(auto, callback) {
    if(auto) {
        if ($(this).width() < 1000) {
            rightPanelIndent(callback);
        }else {
            $(".fw-layout-right").next().removeClass("fw-layout-left-container-extension");
            $(".fw-layout-right").next().addClass("fw-layout-left-container-shrink");
        }
    }else {
        rightPanelIndent(callback);
    }

    // 操作栏-展开/折叠
    $('.fw-layout-right .foldbar-outdent').on('click', function () {
        rightPanelOutdent(callback);
    });
    $('.fw-layout-right .foldbar-indent').on('click', function () {
        rightPanelIndent(callback);
    });
    // 操作栏-展开/折叠
    function rightPanelOutdent(callback) {
        $(".fw-layout-right").next().removeClass("fw-layout-left-container-extension");
        $(".fw-layout-right").next().addClass("fw-layout-left-container-shrink");
        $(".fw-layout-right").removeClass("fw-layout-right-indent");
        $(".fw-layout-right").addClass("fw-layout-right-outdent");
        $(".fw-layout-right .panel-header, .fw-layout-right .panel-wrapper").removeClass("am-hide");
        /*$(".fw-layout-right .foldbar-outdent").addClass("am-hide");
        $('.fw-layout-right .foldbar-indent').removeClass("am-hide");*/
        if (typeof callback == "function") {
            callback("outdent");
        }
    }
    function rightPanelIndent() {
        $(".fw-layout-right").next().removeClass("fw-layout-left-container-shrink");
        $(".fw-layout-right").next().addClass("fw-layout-left-container-extension");
        $(".fw-layout-right .panel-header, .fw-layout-right .panel-wrapper").addClass("am-hide");
        $(".fw-layout-right").removeClass("fw-layout-right-outdent");
        $(".fw-layout-right").addClass("fw-layout-right-indent");
        /*$(".fw-layout-right .foldbar-outdent").removeClass("am-hide");
        $('.fw-layout-right .foldbar-indent').addClass("am-hide");*/
        if (typeof callback == "function") {
            callback("indent");
        }
    }
}

function scrollByWhell(selectors) {
    // 滚轮控制横向滑动
    var div = document.querySelector(selectors);
    div.addEventListener("wheel", function (e) {
        //这里使用的是 chrom浏览器测试的,有一些Api不太准确 ,请大家注意!!!!
        let left = -e.wheelDelta || e.deltaY / 2;
        // console.log('wheelDelta:',-e.wheelDelta,"deltaY :" , e.deltaY);
        div.scrollLeft = div.scrollLeft + left;
    });
}

function domReady(fn) {

    var isReady = false,

        ready = function(){
            if(!isReady){
                typeof fn === 'function' && fn.call(document);
                isReady = true;
            }
        },

        DOMContentLoaded = function() {
            if ( document.addEventListener ) {
                document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                ready();
            } else if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", DOMContentLoaded );
                ready();
            }
        };

    if ( document.readyState === "complete" ) {
        setTimeout( ready, 1 );
    } else if ( document.addEventListener ) {
        document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
        window.addEventListener( "load", ready, false );
    } else {
        document.attachEvent( "onreadystatechange", DOMContentLoaded );
        window.attachEvent( "onload", ready );


        var top = false;

        try {
            top = window.frameElement == null && document.documentElement;
        } catch(e) {}

        if ( top && top.doScroll ) {
            (function doScrollCheck() {
                if ( !isReady ) {
                    try {
                        top.doScroll("left");
                    } catch(e) {
                        return setTimeout( doScrollCheck, 50 );
                    }

                    ready();
                }
            })();
        }
    }
}